package com.liwq.base.atomic;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author : liwq
 * @version : 1.0
 * @date : 2023/2/1
 **/
public class ABADemo {
    public static void main(String[] args) throws InterruptedException {
//        AtomicInteger atomicInteger = new AtomicInteger(100);
//
//
//        new Thread(() -> {
//            atomicInteger.compareAndSet(100, 101);
//            try {
//                TimeUnit.SECONDS.sleep(1);
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//            atomicInteger.compareAndSet(101, 100);//ABA
//        }).start();
//
//        TimeUnit.SECONDS.sleep(1);
//
//
//        new Thread(() -> {
//            atomicInteger.compareAndSet(100, 2022);
//            System.out.println(atomicInteger.get());
//        }).start();




        AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);
        new Thread(() -> {
            System.out.println("线程1版本号" + atomicStampedReference.getStamp());
            atomicStampedReference.compareAndSet(100,101,1,2);
            System.out.println("线程1 第一次修改版本号为" + atomicStampedReference.getStamp());

            atomicStampedReference.compareAndSet(101,100,2,3);
            System.out.println("线程1 第一次修改版本号为" + atomicStampedReference.getStamp());

        }).start();


        new Thread(() -> {
            System.out.println("线程2版本号" + atomicStampedReference.getStamp());

            Boolean b
             = atomicStampedReference.compareAndSet(100,1001,1,3);

            System.out.println("线程2修改" + b);


        }).start();
    }
}
